<template>
  <el-container>
    <el-main>
      <el-form ref="orderForm" :model="form" :rules="rules" label-width="90px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">销售退款</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="memberId">
              <el-select style="width: 100%;" v-model="memberName" :filter-method="remoteMethod" value-key="id"
                         filterable placeholder="请选择客户"
                         @change="selectMember">
                <el-option
                  style="width: 600px;"
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                  <div style="display: flex">
                    <span style="width: 60px;">{{item.code}}</span>
                    <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{ item.mobile }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchMember">搜索客户</div>
                  <div class="elOption1" @click="toAddMember">新增客户</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户订单" prop="memberId">
              <el-select style="width: 100%;" v-model="orderSn" :filter-method="remoteOrder" value-key="id"
                         filterable placeholder="请选择订单" @change="selectOrder">
                <el-option
                  v-for="item in orderData"
                  :key="item.id"
                  :label="item.sn"
                  :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退货仓库" prop="shopId">
              <!-- <div class="input_box">
                <span class="input_box_fz">{{form.shopName?form.shopName:'暂无仓库'}}</span>
              </div> -->
              <el-select value-key="id" style="width: 100%;" v-model="form.shopName" filterable placeholder="请选择仓库" @change="selectShop">
                <el-option
                  v-for="item in shopList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期" prop="memberId">
              <div class="input_box">
                <span class="input_box_fz">{{form.orderDate?form.orderDate:'暂无日期'}}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="11">
            <el-form-item label="收货地址" prop="memberId">
              <div class="input_box">
                <span class="input_box_fz">{{form.address?form.address:'暂无地址'}}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="memberId">
              <div class="input_box">
                <span class="input_box_fz">{{form.phone?form.phone:'暂无电话'}}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="收货人" prop="memberId">
              <div class="input_box">
                <span class="input_box_fz">{{form.consignee?form.consignee:'暂无收货人'}}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
        </div>
        <el-table
          :data="form.itemList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名"
            prop="name"
            >
          </el-table-column>
          <el-table-column
            label="规格"
            max-width="300"
            align="center"
          >
          <template slot-scope="scope">
            <span>{{scope.row.spec}}</span>
          </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
            prop="sn"
          >
          </el-table-column>
          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
          <template slot-scope="scope">
            <span>{{scope.row.unit}}</span>
          </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="center"
            width="70">
          </el-table-column>
          <el-table-column
            label="单价"
            width="120"
            prop="price"
            >
          </el-table-column>
          <el-table-column
            label="金额"
            width="120"
            align="right"
            prop="subTotal"
          >
          </el-table-column>
          <el-table-column
            label="可退数量"
            width="120"
            align="right"
            prop="availableReturnQuantity"
          >
          </el-table-column>
          <el-table-column
            label="实退数量"
            width="120"
            align="right"
            prop="returnQuantity"
          >
          <template slot-scope="scope">
            <el-input style="text-align: right;" @blur="blurClick($event,scope.$index)" @input="numberInput($event,scope.$index)" type="number" v-model="scope.row.returnQuantity"/>
          </template>
          </el-table-column>
        </el-table>
        <div
          style="background-color: #EBEEF5;width: 100%;border-left: 1px solid #DCDFE6;border-right: 1px solid #DCDFE6;border-bottom: 1px solid #DCDFE6;display: flex;justify-content: space-between;padding: 10px;">
          <div>
            <div style="display: flex;margin-left: 10px;align-items: center;height: 40px;">
                <span style="font-size: 16px;color: #606266">运费：{{freight?freight:0}}</span>
            </div>
            <div style="display: flex;margin-left: 10px;align-items: center;height: 40px;">
                <span style="font-size: 16px;color: #606266">退款备注：</span>
                <div style="width: 320px">
                  <el-input placeholder="请输入退款备注" v-model="memo"/>
                </div>
            </div>
          </div>

          <div style="position: relative;width: 290px;">
            <div style="display: flex;margin-left: 10px;align-items: center">
                <span style="font-size: 16px;color: #606266">退款方式：</span>
                <el-select style="" v-model="paymentPluginId" placeholder="请选择状态">
                  <el-option label="原路退回" value="backPayPlugin"></el-option>
                  <el-option label="现金(退回现金)" value="cashPayPlugin"></el-option>
                  <el-option label="转账(非现金退)" value="bankPayPlugin"></el-option>
                  <el-option label="冲账(欠款抵扣)" value="reversePayPlugin"></el-option>
                </el-select>
            </div>
            <div style="display: flex;margin-left: 10px;align-items: center;margin-top: 10px;">
                <span style="font-size: 16px;color: #606266">应退金额：</span>
                <div style="width: 200px">
                  <el-input placeholder="请输入退款备注" v-model="amount"/>
                </div>
            </div>
          </div>
        </div>
        <div style="display: flex;justify-content: flex-end">
          <el-button type="success" v-permission="['askfor.add']" style="margin-top: 20px" :loading="clicked" @click="saveConfirm">保存并确认
          </el-button>
          <el-button :loading="clicked" v-permission="['askfor.add']" style="margin-top: 20px" @click="returnsClick">保存至草稿
          </el-button>
        </div>
      </el-form>
      <!-- 选择客户 -->
      <el-dialog
        title="双击选择客户"
        :visible.sync="memberTableVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="memberTableClose">
        <div style="position: relative;">
          <member-table :key="times" @memberDouble="memberDouble" @memberTableClose="memberTableClose"></member-table>
        </div>
      </el-dialog>
      <!-- 新增客户 -->
      <el-dialog
        title="新增客户"
        :visible.sync="memberVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="memberClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>
<script>
  import {
    mapGetters
  } from 'vuex'
  import {
    EventBus
  } from '@/api/eventBus'
  import {list as memberList} from '@/api/member'
  import {list as orderList,returns, returnsAndAudit} from '@/api/order'
  import {list as shopList} from '@/api/shop'
  import {save,calculate,saveAndConfirm} from '@/api/askfor'
  import utils from '../../utils/utils.js'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import Distpicker from '@/components/Distpicker/Distpicker'
  import OfficeDialog from '@/components/OfficeDialog'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {
    filter
  } from 'jszip/lib/object'
  import memberTable from '@/components/MemberTable/index'
  import memberAdd from '@/views/member/add'
  export default {
    directives: {
      elDragDialog,
      permission
    },
    name: 'askfor-add',
    data() {
      return {
        memberList: [],
        optionHeight: '',
        memberName: '',
        memberTableVisible: false,
        memberVisible: false,
        times: null,
        memberType: 'add',
        orderData:[],
        orderSn:'',
        clicked: false, // 按钮防双击
        shopList:[],
        memo:'',
        paymentPluginId:'backPayPlugin',
        amount:0,
        freight:0,
        form:{
           memberId:'',
           shopName:'',
           orderDate:'',
           address:'',
           phone:'',
           consignee:'',
           shippingMethod:'',
           itemList:[],
           freight:0,
           memo:'',
           paymentVo:[],
           amountPayable:0,
           amountPayable:0,
           offsetAmount:0
        },
        rules: {
          shopId: [
            {required: true, message: '请选择仓库', trigger: 'blur'},
          ],
        },
      }
    },

    created() {
      var _this = this;
      _this.loadMember('');
      _this.loadShop('')
    },
    watch: { // 只要路由发生变化就重新获取数据

    },
    components: {
      memberTable,memberAdd
    },
    filters: {
      watchOrderMethod(val) {
        if (val == 0) {
          return '线上订单'
        } else if (val == 1) {
          return '人工报单'
        } else if (val == 2) {
          return '门店销售'
        }
      },
      watchShippingMethod(val) {
        if (val == 0) {
          return '普通快递'
        } else if (val == 1) {
          return '到店提货'
        } else if (val == 2) {
          return '同城物流'
        }
      },
      watchPayment(val) {
        if (val == 0) {
          return '等待支付'
        } else if (val == 1) {
          return '支付成功'
        } else if (val == 2) {
          return '超时关闭'
        } else if (val == 3) {
          return '付款失败'
        }
      },


    },
    methods: {
      //会员选择
      loadMember(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('keyword', query)
        memberList(params).then(response => {
          console.log(response);
          _this.memberList = response.data.data
          if (_this.memberList.length > 4) {
            this.optionHeight = 'height:35px'
          } else {
            this.optionHeight = 'height:55px'
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      remoteMethod(query) {
        this.loadMember(query)
      },
      selectMember(data) {
        var _this = this;
        console.log(data);
        if (data == '#') {
          _this.memberVisible = true;
          this.times = new Date().getSeconds()
        } else if (data == '/') {
          _this.memberName = ''
          _this.memberTableVisible = true
        } else {
          _this.form.memberId = data.id;
          // _this.loadMember('')
          _this.orderClick('')
          _this.reactClick()
        }
      },
      toSearchMember() {
        this.memberTableVisible = true
      },
      toAddMember() {
        this.memberVisible = true;
        this.times = new Date().getSeconds()
      },
      memberTableClose() {
        this.memberTableVisible = false
      },
      memberDouble(data) {
        var _this = this
        this.form.memberId = data.id;
        this.memberName = data.name
        this.memberTableVisible = false
        this.orderClick('')
        this.reactClick()
      },
      memberClose() {
        this.memberVisible = false;
        this.memberName = '';
      },
      memberClick(data) {
        var _this = this;
        _this.memberName = data.name;
        _this.form.memberId = data.id;
        _this.memberVisible = false;
        _this.orderClick('')
        _this.reactClick()
      },
      // 查询订单
      orderClick(query){
        var _this = this
        orderList({memberId:_this.form.memberId,orderSn:query}).then(res=>{
          console.log(res)
          _this.orderData = res.data.data
        })
      },
      selectOrder(data){
        console.log(data)
        var _this = this
        _this.orderSn = data.sn
        _this.form = data
        _this.form.shopName=data.shopName
        _this.form.itemList.forEach(function(item){
          item.returnQuantity = item.availableReturnQuantity
        })
        _this.calculateClick()
      },
      remoteOrder(query){
        var _this = this
        _this.orderClick(query)
      },
      // 退货
      returnsClick(){
        var _this = this
        var adopt = 0 // 用于判断退货量是否小于0
        this.form.itemList.forEach(item => {
          if (item.returnQuantity > 0) {
            adopt = adopt + item.returnQuantity
          }
        })
        console.log(adopt)
        if (adopt==0) {
          this.$message({message: '请输入退货数量',type: 'warning'})
          return;
        }
        if(utils.isNull(_this.form.shopId)){
          _this.$message({message:'请选择仓库',type:'warning'})
          return
        }
        let params = new URLSearchParams();
        params.append('shopId', _this.form.shopId);
        params.append('memo',_this.memo)
        params.append('orderId',_this.form.id)
        params.append('amount',_this.amount)
        params.append('paymentPluginId',_this.paymentPluginId)
        _this.clicked = true
        save(_this.form.itemList,params).then(response => {
          console.log(response);
          _this.clicked = false
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
          EventBus.$emit('askfor-add', response.data)
          _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
            _this.$router.push({
              path: '/askfor/list'
            })
          })
        }).catch(error => {
          _this.clicked = false
          console.log('error!!')
        });
      },
      // 保存并确认
      saveConfirm(){
        var _this = this
        var adopt = 0 // 用于判断退货量是否小于0
        this.form.itemList.forEach(item => {
          if (item.returnQuantity > 0) {
            adopt = adopt + item.returnQuantity
          }
        })
        console.log(adopt)
        if (adopt==0) {
          this.$message({message: '请输入退货数量',type: 'warning'})
          return;
        }
        if(utils.isNull(_this.form.shopId)){
          _this.$message({message:'请选择仓库',type:'warning'})
          return
        }
        let params = new URLSearchParams();
        params.append('shopId', _this.form.shopId);
        params.append('memo',_this.memo)
        params.append('orderId',_this.form.id)
        params.append('amount',_this.amount)
        params.append('paymentPluginId',_this.paymentPluginId)
        _this.clicked = true
        saveAndConfirm(_this.form.itemList,params).then(response => {
          console.log(response);
          _this.clicked = false
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
          EventBus.$emit('askfor-add', response.data)
          _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
            _this.$router.push({
              path: '/askfor/list'
            })
          })
        }).catch(error => {
          _this.clicked = false
          console.log('error!!')
        });
      },
      reactClick(){
        this.form = {
           memberId:'',
           shopName:'',
           orderDate:'',
           address:'',
           phone:'',
           consignee:'',
           shippingMethod:'',
           itemList:[],
           freight:0,
           memo:'',
           paymentVo:[],
           amountPayable:0,
           amountPayable:0,
           offsetAmount:0
        }
        this.orderSn = '',
        this.memo='',
        this.paymentPluginId='backPayPlugin',
        this.amount=0
      },
      selectShop(data){
        this.form.shopName=data.name
        this.form.shopId=data.id
        this.$forceUpdate()
      },
      loadShop(query) {
        let params = new URLSearchParams()
        params.append('name', query)
        shopList(params).then(res => {
          this.shopList = res.data.data
        })
      },
      calculateClick(){
        var _this = this
        calculate(_this.form.id,_this.form.itemList).then(res=>{
          _this.amount = res.data.amountPayable
          _this.freight = res.data.freight
        })
      },
      numberInput (value, index) { // 限制最大退货数量跟最小退货数量
        if (value > this.form.itemList[index].availableReturnQuantity) {
          this.form.itemList[index].returnQuantity = this.form.itemList[index].availableReturnQuantity
          console.log('退款输入框')
          // this.calculateClick()
        }
        if(value > 0){
          this.calculateClick()
        }
      },
      blurClick(value,index){
        console.log(value)
        console.log(index)
        if(this.form.itemList[index].returnQuantity <= 0 || this.form.itemList[index].returnQuantity == ''){
          this.form.itemList[index].returnQuantity = 0
          this.calculateClick()
        }
      }
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }

  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    padding-right: 20px;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }

  .input_box {
    width: 100%;
    height: 36px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding-left: 15px;
    padding-right: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .input_box_fz {
    color: #909399;
  }

  .payInput_Box {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding-left: 15px;
    padding-right: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
</style>
